// service/addressmanager/addressmanager.js
const app = getApp()
import http from "../../utils/http"
import util from "../../utils/util"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    choosedid:'',
    list:[],
    finish: false,
    loading: false,
    page: 1,
    type: 0,
    safeBottom: `30px`,
  },
  //添加新地址
  toaddnewaddress(){
    util.skip('/service/addnewaddress/addnewaddress',{
      saveAddress:()=>{
        this.reload()
      }
    })
  },
  change(e){
    util.skip('/service/addnewaddress/addnewaddress?type=edit',{
      saveAddress:()=>{
        this.reload()
      }
    }, (res)=>{
      res.eventChannel.emit('editInfo', e.currentTarget.dataset.info)
    })
  },
  del(e){
    let index = e.currentTarget.dataset.index
    let id = e.currentTarget.dataset.id
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除这个地址吗？',
      success: (res) => {
        if (res.confirm) {
          http.post('address/handleaddress', {
            type: 'del',
            id: id
          }).then(res => {
            util.toast(res.msg)
            this.data.list.splice(index,1)
            this.setData({
              list: this.data.list
            })
          })
        }
      }
    })
    
  },
  chooseaddress(e){
    if(this.data.type == 1){
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('selectAddress',e.currentTarget.dataset.item);
      util.back();
    }
    

  },

  reload(){
    this.setData({
      list: [],
      page: 1,
      finish: false
    })
    this.getList()
  },
  more(){
    this.setData({
      page: ++this.data.page
    })
    this.getList()
  },
  getList(){
    if(this.data.finish){
      return 
    }
    if(this.data.loading){
      return 
    }
    this.setData({
      loading: true
    })
    http.get('address/addresslist', {
      page: this.data.page,
    }).then(res => {
      if(res.data.length === 0){
        this.setData({
          finish: true
        })
      }
      let arr = this.data.list.concat(res.data)
      this.setData({
        list: arr
      })
      
    }).finally(res => {
      this.setData({
        loading: false
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const high = app.globalData.safeBottom
    this.setData({
      safeBottom: `${high}px`
    })
    if(options.type){
      this.setData({
        type: options.type
      })
    }
    
    this.reload()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})